package userPages;
import pages.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DBUtils;

/**
 * Servlet implementation class DeleteReservation
 */
public class DeleteReservation extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public DeleteReservation() {
		super();

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		Connection conn = null;
		PreparedStatement updateUserStmt = null;
		ResultSet rs = null;
		try {
			String id = request.getParameter("instrId");
			String startTime = request.getParameter("startTime");

			DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (formatter.parse(startTime).after(
					Calendar.getInstance().getTime())) {

				String userLogin = LMUtils.getUserLogin(request);
				conn = DBUtils.getConnection();
				updateUserStmt = conn
						.prepareStatement("DELETE from reservations where userlogin=? && instrumentID=? && startTime=?;");
				updateUserStmt.setString(1, userLogin);
				updateUserStmt.setString(2, id);
				updateUserStmt.setString(3, startTime);
				updateUserStmt.execute();
			}
		} catch (Exception e) {
			response.sendError(403);
		} finally {
			DBUtils.close(rs);
			DBUtils.close(updateUserStmt);
			DBUtils.close(conn);
		}

		response.getWriter().flush();
		response.getWriter().close();
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

}
